//
//  DetailViewController.m
//  Qyer
//
//  Created by dllo on 15/10/19.
//  Copyright (c) 2015年 GF. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, UIActionSheetDelegate, UIPopoverPresentationControllerDelegate>
@property (nonatomic, strong)NSMutableArray *listArr;
@property (nonatomic, assign)CGFloat height;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UIScrollView *line;
@property (nonatomic, weak)NSString *typeString;
@property (nonatomic, assign)BOOL pageChange;
@property (nonatomic, assign)CGFloat offsetX;
@property (nonatomic, strong)UIView *navBar;
@property (nonatomic, strong)UIAlertController *alertController;
@property (nonatomic, strong)NSArray *moreArr;
@property (nonatomic, strong)UITableView *moreTable;
@property (nonatomic, strong)UIView *coverView;
@property (nonatomic, strong)UILabel *typeLabel;
@end

@implementation DetailViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    if (_myTableView == nil) {
        [GiFHUD show];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [GiFHUD dismiss];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _listArr = [[NSMutableArray alloc] init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.page = 1;
    self.tabBarController.tabBar.hidden = YES;
    [self createCustomNavigationBar];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(popClick)];
    self.navigationController.navigationBar.alpha = 0.5;
    
    [GiFHUD setGifWithImageName:@"9707070_11.gif"];
    
    [self getData];
    [self createMoreTable];
    
}
- (void)createCustomNavigationBar {
    _navBar = [[UIView alloc] initWithFrame:CRM(0, 0, SCREEN_WIDTH, 64)];
    _navBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _navBar.layer.borderWidth = 0;
    _navBar.alpha = 0;
    _navBar.backgroundColor = NAVBAR_COLOR;
    [self.view addSubview:_navBar];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(20, 30, 25, 20);
    [backButton setImage:[UIImage imageNamed:@"fanhui-white"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CRM(0, 0, 200, 30)];
    label.center = CGPointMake(_navBar.center.x, _navBar.center.y + 10);
    NSLog(@"dic - %@", self.dic);
    label.text = [self.dic objectForKey:@"name"];
    label.textColor = WHITE_COLOR;
    [self.view addSubview:backButton];
    [self.view addSubview:label];
}
- (void)backClick {
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createMoreTable {
    _moreArr = [self.dic objectForKey:@"types"];
    _alertController = [UIAlertController alertControllerWithTitle:@"论坛主题" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i < _moreArr.count; i++) {
        UIAlertAction *actionSheet = [UIAlertAction actionWithTitle:[_moreArr[i] objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _pageChange = YES;
            self.page = 1;
            [GiFHUD show];
            [self getMoreDataWithStr:[_moreArr[i] objectForKey:@"id"]];
            _typeLabel.hidden = NO;
            _typeLabel.text = [_moreArr[i] objectForKey:@"name"];
        }];
        [_alertController addAction:actionSheet];
    }
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [_alertController addAction:cancel];
}
- (void)getMoreDataWithStr:(NSString *)str {
    if ([Reachability isConnectedInternet]) {
        [AFN getdataWithString:[NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%@&forum_type=%@&lat=38.88256080128168&lon=121.5397561064435&oauth_token=aa3e2c9cfa1fa80cc75956eeb20534b3&page=%ld&type=all&v=1", [_dic objectForKey:@"id"], str, self.page] block:^(id block) {
            if (_pageChange == YES) {
                [_myTableView setContentOffset:CGPointMake(0, - 160) animated:NO];
                [_listArr removeAllObjects];
            }
            for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"entry"]) {
                PostModel *model = [PostModel modelWithDictionary:dic];
                [_listArr addObject:model];
            }
            NSLog(@"count == %ld", _listArr.count);
            [_myTableView reloadData];
            [_myTableView.legendFooter endRefreshing];
            [GiFHUD dismiss];
        } BLOCK:^(id BLOCK) {
            
        }];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    _navBar.alpha = 0.006 * (_myTableView.contentOffset.y + 160);
    if (y < 0) {
        CGRect frame = _imageView.frame;
        // 坐标状态
        frame.origin.y = - (y + 300) * 0.55;
        // 高度状态
        //frame.size.height = -y + 64;
        _imageView.frame = frame;
        //NSLog(@"y == %f", y);
        if (y > - 180) {
            _myTableView.contentInset = UIEdgeInsetsMake(- y, 0, 0, 0);
        }
    }
    if (y > 0) {
        _myTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    }
}
- (void)popClick {
    self.navigationController.navigationBar.alpha = 1;
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark - create table
- (void)creatTableView {
    _imageView = [[UIImageView alloc] initWithFrame:CRM(0, - SCREEN_WIDTH / 5 + 20 * HEIGHT, SCREEN_WIDTH, SCREEN_WIDTH)];
    //UIImage *image = [UIImage imageNamed:[_dic objectForKey:@"photo"]];
    
    [_imageView sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"photo"]]];
    _imageView.image = [UIImage imageWithBlurImage:_imageView.image intputRadius:2.0f];
    [self.view insertSubview:_imageView atIndex:0];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CRM(0, 0, SCREEN_WIDTH, 64)];
    headerView.backgroundColor = [UIColor clearColor];
    UIImageView *userHead = [[UIImageView alloc] initWithFrame: CRM(20, - 25, 80, 80)];
    userHead.layer.borderWidth = 3;
    userHead.layer.borderColor = WHITE_COLOR.CGColor;
    userHead.layer.cornerRadius = 5;
    [userHead.layer setMasksToBounds:YES];
    [userHead sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"photo"]]];
    [headerView addSubview:userHead];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(110, 20, 180, 25)];
    label.text = [NSString stringWithFormat:@"%@个帖子", [_dic objectForKey:@"total_threads"]];
    label.textColor = WHITE_COLOR;
    [headerView addSubview:label];
    
    _typeLabel = [[UILabel alloc]initWithFrame:CRM(SCREEN_WIDTH - 100, 20, 80, 25)];
    _typeLabel.hidden = YES;
    _typeLabel.backgroundColor = [UIColor clearColor];
    
    _typeLabel.textColor = WHITE_COLOR;
    _typeLabel.textAlignment = NSTextAlignmentRight;
    [headerView addSubview:_typeLabel];
    
    _myTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    _myTableView.dataSource = self;
    _myTableView.delegate = self;
    _myTableView.contentInset = UIEdgeInsetsMake(160 * HEIGHT, 0, 0, 0);
    _myTableView.backgroundColor = [UIColor clearColor];
    _myTableView.tableFooterView = view;
    _myTableView.tableHeaderView = headerView;
    _myTableView.sectionHeaderHeight = 48;
    [self.view insertSubview:_myTableView atIndex:1];
}

#pragma mark - 网络请求
- (void)getData {
    if ([Reachability isConnectedInternet]) {
        [AFN getdataWithString:[NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%@&lat=38.88259977358427&lon=121.5397371891666&page=%ld%@", [_dic objectForKey:@"id"], self.page, self.typeString] block:^(id block) {
            if (_pageChange == YES) {
                [_myTableView setContentOffset:CGPointMake(0, - 160) animated:NO];
                [_listArr removeAllObjects];
            }
            for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"entry"]) {
                PostModel *model = [PostModel modelWithDictionary:dic];
                [_listArr addObject:model];
            }
            NSLog(@"count == %ld", _listArr.count);
            if (_myTableView == nil) {
                NSLog(@"creatTableView");
                self.title = [_dic objectForKey:@"name"];
                [self creatTableView];
                [self addFooter];
            } else {
                [_myTableView reloadData];
                NSLog(@"reloadData");
            }
            [_myTableView.legendFooter endRefreshing];
            [GiFHUD dismiss];
        }
        BLOCK:^(id BLOCK) {
            
        }];
    }
}
#pragma mark 上拉加载
- (void)addFooter {
    DetailViewController *detail = self;
    [_myTableView addLegendFooterWithRefreshingBlock:^{
        _pageChange = NO;
        _page = _page + 1;
        [detail getData];
    }];
}
- (void)pageChange:(UIButton *)sender {
    self.page = 1;
    [_line setContentOffset:CGPointMake(- sender.frame.origin.x, 0) animated:YES];
    _offsetX = - sender.frame.origin.x;
    NSArray *array = @[@"", @"&type=new", @"&type=digest"];
    if (sender.tag != 13) {
        _typeLabel.hidden = YES;
        self.typeString = array[sender.tag - 10];
        _pageChange = YES;
        NSLog(@"type == %@", self.typeString);
        [GiFHUD show];
        [self getData];
    } else {
        [self presentViewController:_alertController animated:YES completion:nil];
    }
}
//- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController {
//    return NO;
//}
#pragma mark - 换页section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGFloat y = _myTableView.sectionHeaderHeight;
    UIView *view = [[UIView alloc] initWithFrame:CRM(0, 0, SCREEN_WIDTH, y)];
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = [UIColor lightGrayColor].CGColor;
    view.backgroundColor = [UIColor whiteColor];
    NSArray *array = @[@"全部", @"最新", @"精华", @"更多"];
    for (int i = 0; i < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CRM(i * SCREEN_WIDTH / 4, 0, SCREEN_WIDTH / 4, y - 3);
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTag:10 + i];
        [button addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CRM(0, 0, SCREEN_WIDTH / 4, 3)];
    lineView.backgroundColor = LIGHT_GREEN;
    _line = [[UIScrollView alloc] initWithFrame:CRM(0, y - 3, SCREEN_WIDTH, 3)];
    _line.contentSize = CSM(_line.frame.size.width * 2, 0);
    _line.bounces = NO;
    _line.pagingEnabled = YES;
    _line.backgroundColor = [UIColor clearColor];
    [_line addSubview:lineView];
    _line.contentOffset = CGPointMake(_offsetX, 0);
    [view addSubview:_line];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return self.height;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _listArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cell";
    CellForPostModel *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[CellForPostModel alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    PostModel *model = [_listArr objectAtIndex:indexPath.row];
    [cell setData:model text:@""];
    self.height = cell.height + 80 ;
    return cell;
    
}
#pragma mark - 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PostModel *model = [_listArr objectAtIndex:indexPath.row];
    CommunityWeb *web = [[CommunityWeb alloc] init];
    web.urlStr = model.view_url;
    [self.navigationController pushViewController:web animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
